/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pl.cezary.butler.walili.server.db.tasks;

import java.sql.SQLException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.activation.MimetypesFileTypeMap;
import pl.cezary.butler.walili.server.db.tables.ZadReszta;
import pl.cezary.butler.walili.server.db.utils.TableDefinitionUtils;

/**
 *
 * @author czarek
 */
public class FillMimeTypesTask extends UpdateTask {

    private static final Logger log = Logger.getLogger(FillMimeTypesTask.class.getName());
    private static final String DEFAULT = "text/html";
    private static final String AUDIO = "audio/mpeg3";
    private final boolean doAll;

    public FillMimeTypesTask(boolean doAll) {
        super();
        this.doAll = doAll;
    }

    public FillMimeTypesTask() {
        this(false);
    }
    
    

    @Override
    public void execute() throws SQLException {
        if(doAll)
            getJdbcTemplate().update("update zad_reszta set mime_type = null;");
        final int mp3 = getJdbcTemplate().update("UPDATE zad_reszta SET mime_type=? WHERE mime_type IS NULL AND lower(cel) LIKE ?", AUDIO, "%.mp3");
        log.log(Level.INFO, "{0} files marked as mp3",mp3);
        final int html = getJdbcTemplate().update("UPDATE zad_reszta SET mime_type=? WHERE mime_type IS NULL AND lower(cel) LIKE ? OR lower(cel) LIKE ? OR cel NOT LIKE ?", DEFAULT, "%.htm", "%.html", "%.___");
        log.log(Level.INFO, "{0} files marked as html",html);
        final List<String> rest = getJdbcTemplate().queryForList(TableDefinitionUtils.getQueryForColumn(ZadReszta.celUrl) + String.format(" WHERE %s IS NULL", ZadReszta.mime_type), String.class);
        for (final String celUrl : rest) {
            String mimeType = MimetypesFileTypeMap.getDefaultFileTypeMap().getContentType(celUrl);
            if (mimeType == null) {
                mimeType = DEFAULT;
            }
            log.log(Level.INFO, "Guessed mime type for {0} is {1}",new Object[]{celUrl,mimeType});
            int count = getJdbcTemplate().update("UPDATE zad_reszta SET mime_type=? WHERE celUrl=?", mimeType,celUrl);
            assert(count==1);            
        }

    }
}
